import os
import sys
import tempfile
import wx
import wx.tools.img2py as img2py

STATE_NEW = 0
STATE_CHANGED = 1
STATE_BUILT = 2
STATE_SAVED = 3
class ImageModel(object):
    """
 Class to model the list of Images being processed and associated data
    """
    def __init__(self):
        self.options={"cdir":os.getcwd(),"name":True,"compat":False,
            "catalog":False}
        self.state = STATE_NEW
    
    def setOption(self,option,value):
        self.options[option]=value
           
    def getOption(self,option,default=None):
        return self.options[option] if option in self.options else default
        
    def doBuild(self,filelist):
        self.filelist = filelist
        tfname=tempfile.mktemp()
        try:
           self._doBuild(tfname)
           self.pythonline = [line for line in open(tfname)]
           self.state = STATE_BUILT
        finally:
            if os.path.exists(tfname): os.remove(tfname)
                
    def _doBuild(self,python_file):
        out = open(python_file,"w")
        out.write("#" + "-" * 70 + "\n")
        out.write("# This file was generated by %s\n" % sys.argv[0])
        optlist = [(name,self.getOption(name))
             for name in ["name","inclext","catalog","compat","icon"]]
        optstr = ",".join(["%s:%s" % (name,value) 
             for (name,value) in optlist if value !=None])
        out.write("# Using options {%s}\n\n" % optstr)
        out.write("from wx.lib.embeddedimage import PyEmbeddedImage\n\n")  
        out.close()
        
        for name,imagefile in self.filelist:
            out = open(python_file,"a")
            out.write("#" + "-" * 70 + "\n")
            out.write("# PyEmbeddedImage generated from %s\n" % imagefile)
            out.close()
            img2py.img2py(imagefile,python_file,append=True,
                   imgName=name if self.getOption("name") else "",
                   catalog=self.getOption("catalog",False),
                   functionCompatible=self.getOption("compat",False),
                   icon=self.getOption("icon",False))
                   
    def CanBuild(self):
        return not self.state == STATE_NEW
        
    def doSave(self):
        file = self.getOption("pyfile")
        if file == None: return
        out = open(file,"w")
        out.writelines(self.pythonline)
        out.close()
        self.state = STATE_SAVED
        
    def CanSave(self):
        return self.state == STATE_BUILT    
     
    def CanSaveAs(self):
        return self.state in (STATE_BUILT,STATE_SAVED)    
           
    def doChange(self):
        self.state = STATE_CHANGED
    
    def CanDestroy(self):
        return self.state in (STATE_NEW,STATE_SAVED)
        
               
    def doLoadFile(self,python_file,filelist):
        if not os.path.exists(python_file): return
        pythonline = [line for line in open(python_file)]
        # extract options
        for line in pythonline:
            if line.find("Using options") > -1:
                options = line.partition("Using options")[2].strip("{ }\n")
                for option in options.split(","): 
                    option=option.split(":")
                    try:
                        self.setOption(option[0],eval(option[1]))
                    except Exception as e:
                        pass           
                break
         # extract filenames
        for line in pythonline:
            if line.find("PyEmbeddedImage generated from") > -1:  
                imgfile = line.partition("PyEmbeddedImage generated from")[2].strip()
                if os.path.exists(imgfile):
                    filelist.Add(imgfile)
                    self.setOption("cdir",os.path.dirname(imgfile))
                    self.setOption("pyfile",python_file)
                    self.state = STATE_SAVED
                else:
                    if wx.MessageDialog(filelist,"Image file \n%s\nnot found"%imgfile,
                     "File error",wx.OK|wx.CANCEL|wx.ICON_ERROR).ShowModal() ==  wx.ID_CANCEL:
                        return False
        
        return True